const { md5 } = require('../../utils/md5.js');
const app = getApp();

Page({
  data: {
    currentTab: "password", // 当前选中的登录方式
    form: { username: "", password: "" }, // 账号密码登录表单
    smsForm: { mobile: "", code: "" }, // 短信验证码登录表单
    countdown: 0, // 验证码倒计时
    timer: null // 倒计时定时器
  },

  onUnload() {
    const { timer } = this.data;
    if (timer) {
      clearInterval(timer);
      this.setData({ timer: null });
    }
  },
  onShow() {
    if (app.globalData.hasLogin) {
      wx.reLaunch({url:'/pages/index/index'});
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
    if (tab === 'sms') {
      this.setData({ smsForm: { mobile: "", code: "" } });
    } else {
      this.setData({ form: { username: "", password: "" } });
    }
  },

  handleUsernameInput(e) {
    this.setData({ "form.username": e.detail.value.trim() });
  },

  handlePasswordInput(e) {
    this.setData({ "form.password": e.detail.value });
  },

  handleMobileInput(e) {
    let mobile = e.detail.value.replace(/\D/g, '');
    if (mobile.length > 11) mobile = mobile.slice(0, 11);
    this.setData({ "smsForm.mobile": mobile });
  },

  handleCodeInput(e) {
    let code = e.detail.value.replace(/\D/g, '');
    if (code.length > 6) code = code.slice(0, 6);
    this.setData({ "smsForm.code": code });
  },


  async login() {
    const { username, password } = this.data.form;
    if (!username.trim()) {
      wx.showToast({ title: '请输入用户名', icon: 'none', duration: 1500 });
      return;
    }
    if (username.trim().length > 20) {
      wx.showToast({ title: '用户名不能超过20个字符', icon: 'none', duration: 1500 });
      return;
    }
    if (!password) {
      wx.showToast({ title: '请输入密码', icon: 'none', duration: 1500 });
      return;
    }

    const encryptedPwd = md5(password);
    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8080/user/login',
        method: 'POST',
        data: { username: username.trim(), password: encryptedPwd },
        header: { 'Content-Type': 'application/json' },
        success: (resp) => resolve(resp),
        fail: (err) => reject(err)
      });
    });

    const { data } = res;
    if (data.code === 200) {
      wx.showToast({ title: data.msg || '登录成功', icon: 'success', duration: 1500 });
      const token = data.data;
      wx.setStorageSync("token", token);
      app.globalData.token = token;
      app.globalData.hasLogin = true;
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/home/index',
          fail: (err) => {
            console.error('跳首页失败：', err);
            wx.showToast({ title: '首页路径配置错误', icon: 'none' });
          }
        });
      }, 1500);
    } else {
      wx.showToast({ title: data.msg || '登录失败', icon: 'none', duration: 1500 });
    }
  },

  async sendSmsCode() {
    const { mobile } = this.data.smsForm;
    const { countdown } = this.data;
    if (countdown > 0) {
      wx.showToast({ title: `请${countdown}秒后再试`, icon: 'none', duration: 1500 });
      return;
    }
    if (!mobile) {
      wx.showToast({ title: '请输入手机号', icon: 'none', duration: 1500 });
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none', duration: 1500 });
      return;
    }

    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8080/sendSmsCode',
        method: 'POST',
        data: { mobile },
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (resp) => resolve(resp),
        fail: (err) => reject(err)
      });
    });

    const { data } = res;
    if (data.code === 200) {
      wx.showToast({ title: data.msg || '验证码已发送', icon: 'success', duration: 1500 });
      this.setData({ "smsForm.code": "" });
      this.startCountdown();
    } else {
      wx.showToast({ title: data.msg || '发送失败', icon: 'none', duration: 1500 });
    }
  },

  startCountdown() {
    const initCount = 60;
    this.setData({ countdown: initCount });
    const timer = setInterval(() => {
      this.setData(prev => {
        const newCount = prev.countdown - 1;
        if (newCount <= 0) {
          clearInterval(timer);
          return { countdown: 0, timer: null };
        }
        return { countdown: newCount };
      });
    }, 1000);
    this.setData({ timer });
  },

  async smsLogin() {
    const { mobile, code } = this.data.smsForm;
    if (!mobile) {
      wx.showToast({ title: '请输入手机号', icon: 'none', duration: 1500 });
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none', duration: 1500 });
      return;
    }
    if (!code || code.length !== 6) {
      wx.showToast({ title: '请输入6位验证码', icon: 'none', duration: 1500 });
      return;
    }

    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8080/user/smsLogin',
        method: 'POST',
        data: { mobile, code },
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        success: (resp) => resolve(resp),
        fail: (err) => reject(err)
      });
    });

    const { data } = res;
    if (data.code === 200) {
      wx.showToast({ title: data.msg || '登录成功', icon: 'success', duration: 1500 });
      const token = data.data;
      if (token) {
        wx.setStorageSync("token", token);
        app.globalData.token = token;
        app.globalData.hasLogin = true;
      }
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index',
          fail: (err) => {
            console.error('跳首页失败：', err);
            wx.showToast({ title: '首页路径配置错误', icon: 'none' });
          }
        });
      }, 1500);
    } else {
      wx.showToast({ title: data.msg || '登录失败', icon: 'none', duration: 1500 });
    }
  },

  goToRegistered() {
    wx.navigateTo({
      url: '/pages/register/register',
      fail: (err) => {
        console.error('跳转注册页失败：', err);
        if (err.errMsg.includes('page "pages/register/register" is not found')) {
          wx.showToast({ title: '注册页面未在app.json注册', icon: 'none' });
        } else {
          wx.showToast({ title: '跳转失败，请检查页面路径', icon: 'none' });
        }
      }
    });
  }
});